<script>
    layui.config({
        base: '/static/customAdmin/'
    }).extend({
        index: 'lib/index'
    }).use(['index', 'form', 'admin', 'rate', 'table', 'laytpl', 'upload'], async () => {

        const form = layui.form, admin = layui.admin, rate = layui.rate, table = layui.table, laytpl = layui.laytpl, upload = layui.upload, $ = layui.$;
        let contacts_lists = []
            , foreign_lists = []
            , seal_lists = [];

        rate.render({
            elem: '#control_rating'
            , theme: 'rgb(255, 204, 0)'
            , value: @{{ .m.ControlRating }}
            , choose: function (value) {
                $("input[name='ControlRating']").val(value);
            }
        });


        if (@{{ .m.Id }}) {
            table.render({
                elem: '#contacts_lists_new'
                , autoSort: false
                , method: 'post'
                , where: {
                    CompanyId: @{{.m.Id}},
                    order: 'desc',
                    sort: 'CreatedAt'
                }
                , contentType: 'application/json'
                , url: @{{ urlfor "CompanyContactController.DataGrid" }}
                , request: {
                    pageName: 'offset' //页码的参数名称，默认：page
                    , limitName: 'limit' //每页数据量的参数名，默认：limit
                }, response: {
                    statusName: 'code',
                    statusCode: 0,
                }, parseData: function (res) {
                    return {
                        "code": res.code,
                        "count": res.total,
                        "data": res.rows
                    };
                }
                , toolbar: true
                , defaultToolbar: ['filter']
                , colFilterRecord: 'local', cols: [[
                    {
                        field: 'name', title: '姓名', templet: function (data) {
                            if (data.IsAdmin) {
                                return `<span class="blue">${data.Name}</span><span class="contacts_admin">管理员</span>`
                            } else {
                                return `<span class="blue">${data.Name}</span>`
                            }
                        }
                    }
                    , {field: 'Offer', title: '职位'}
                    , {field: 'Phone', title: '手机号'}
                    , {field: 'Email', title: '邮箱地址'}
                    , {field: 'ICCode', title: 'IC卡号'}
                    , {field: 'Remark', title: '备注'}
                    , {title: '操作', toolbar: '#contacts_lists_toolbar', width: 120}
                ]]
                , data: contacts_lists
                , skin: 'line'
            });

            $("#contacts_new").on('click', function () {
                layer.open({
                    type: 2,
                    title: '新增联系人',
                    shadeClose: true,
                    area: admin.screen() < 2 ? ['80%', '300px'] : ['700px', '600px'],
                    content:`/company_contact/create/` +@{{ .m.Id }},
                });
            });

            table.on('tool(contacts_lists_new)', function (obj) {
                const data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        await admin.delete(`/company_contact/delete/${data.Id}`, obj);
                        layer.close(index);
                        self.location.reload();
                    });
                } else if (obj.event === 'edit') {
                    const data = obj.data;
                    layer.open({
                        type: 2,
                        title: '编辑联系人',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['700px', '600px'],
                        content: `/company_contact/edit/${data.Id}`
                    });
                    $("#offer_edit").find(`option[value='${data.Offer}']`).prop('selected', true);
                }
            });


            table.render({
                elem: '#foreign_lists_new'
                , autoSort: false
                , method: 'post'
                , where: {
                    CompanyId: @{{ .m.Id }},
                    order: 'desc',
                    sort: 'CreatedAt'
                }
                , contentType: 'application/json'
                , url: @{{ urlfor "CompanyForeignController.DataGrid" }}
                , request: {
                    pageName: 'offset' //页码的参数名称，默认：page
                    , limitName: 'limit' //每页数据量的参数名，默认：limit
                }, response: {
                    statusName: 'code',
                    statusCode: 0,
                }, parseData: function (res) {
                    return {
                        "code": res.code,
                        "count": res.total,
                        "data": res.rows
                    };

                }
                , toolbar: true
                , defaultToolbar: ['filter']
                , cols: [[
                    {
                        field: 'ForeignCompanyChapter', title: '外商章', templet: function (data) {
                            return `<img src="${data.ForeignCompanyChapter}" />`
                        }
                    }
                    , {field: 'ForeignCompanyName', title: '外商公司名称'}
                    , {field: 'ForeignCompanyAddress', title: '外商公司地址'}
                    , {field: 'ForeignCompanyPhone', title: '外商公司电话'}
                    , {title: '操作', toolbar: '#foreign_lists_toolbar', width: 120}
                ]]
                , data: foreign_lists
                , skin: 'line'
            });

            $("#foreign_new").on('click', function () {
                layer.open({
                    type: 2,
                    title: '新增外商公司',
                    shadeClose: true,
                    area: admin.screen() < 2 ? ['80%', '600px'] : ['800px', '600px'],
                    content: `/company_foreign/create/`+@{{ .m.Id }}
                });

                upload.render({
                    elem: '#foreign_company_chapter'
                    , url: '/image/upload'
                    , accept: 'images'
                    , acceptMime: 'image/png'
                    , field: 'image'
                    , size: 500
                    , done: function (data) {
                        $("#foreign-upload-img").attr('src', data.url);
                    }
                });
            });

            table.on('tool(foreign_lists_new)', function (obj) {
                const data = obj.data;
                if (obj.event === 'del') {
                    layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                        await admin.delete(`/company_foreign/delete/${data.Id}`, obj);
                        layer.close(index);
                        self.location.reload();
                    });
                } else if (obj.event === 'edit') {
                    layer.open({
                        type: 2,
                        title: '编辑外商公司',
                        shadeClose: true,
                        area: admin.screen() < 2 ? ['80%', '300px'] : ['800px', '600px'],
                        content: `/company_foreign/edit/${data.Id}`
                    });
                    form.render();
                }
            });


            laytpl($("#seal_lists_templet").html()).render(seal_lists, (html) => {
                $("#seal_lists_new").html(html);
            });

            $("body").on("mouseenter mouseleave", ".seal_flex_img", function () {
                $(this).find(".seal_flex_edit").fadeToggle()
            });

            $("body").on('click', '.seal_flex_edit_btn', function () {
                layer.open({
                    type: 2,
                    title: '编辑公章',
                    shadeClose: true,
                    area: admin.screen() < 2 ? ['80%', '550px'] : ['700px', '550px'],
                    content: `/company_seal/edit/${$(this).data('id')}`
                });
            });

            $("body").on('click', '.seal_flex_edit_del', function () {
                layer.confirm('真的删除么', {title: '提示'}, async (index) => {
                    await admin.delete(`/company_seal/delete/${$(this).data('id')}`);
                    layer.close(index);
                    self.location.reload();
                });
            });

            $("#seal_new").on('click', function () {
                layer.open({
                    type: 2,
                    title: '上传公章',
                    shadeClose: true,
                    area: admin.screen() < 2 ? ['80%', '500px'] : ['800px', '500px'],
                    content: `/company_seal/create/`+@{{ .m.Id }}
                });
            });
        }


        await form.verify({
            sub_phone: function (value, item) {
                if ($("input[name='is_open_phone']").prop("checked")) {
                    if (!value) {
                        return '请输入手机号'
                    }
                    if (!(/^(0?(13|14|15|18|17)[0-9]{9},)*0?(13|14|15|18|17)[0-9]{9}$/.test(value))) {
                        return "请正确输入手机号"
                    }
                }
            }
            , sub_email: function (value, item) {
                if ($("input[name='IsOpenSubEmail']").prop("checked")) {
                    if (!value) {
                        return '请输入邮箱'
                    }
                    if (!(/^(([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+,)*([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value))) {
                        return "请正确输入邮箱"
                    }
                }
            }

        });

        if (!($("input[name='IsOpenSubPhone']").prop("checked"))) {
            $(".is_phone_show").hide()
        } else {
            $(".is_phone_show").show()
        }

        if (!($("input[name='IsOpenSubEmail']").prop("checked"))) {
            $(".is_email_show").hide()
        } else {
            $(".is_email_show").show()
        }

        form.on('switch(is_open_phone)', function (data) {
            if (data.elem.checked) {
                $(".is_phone_show").show();
                $(".subscription_content").show();
            } else {
                $(".is_phone_show").hide();
                if (!($("input[name='IsOpenSubEmail']").prop("checked"))) {
                    $(".subscription_content").hide();
                }
            }
        });

        form.on('switch(is_open_email)', function (data) {
            if (data.elem.checked) {
                $(".is_email_show").show();
                $(".subscription_content").show();
            } else {
                $(".is_email_show").hide();
                if (!($("input[name='IsOpenSubPhone']").prop("checked"))) {
                    $(".subscription_content").hide()
                }
            }
        });

        let sub_content_check, sub_content_submit, sub_content_reject, sub_content_pass;
        $("#sub_content_check").on('click', function () {
            if ($(this).text() === "退订") {
                sub_content_check = 0;
                $(this).text("订阅");
                $(this).removeClass("active")
            } else if ($(this).text() === "订阅") {
                sub_content_check = 1;
                $(this).text("退订");
                $(this).addClass("active")
            }
        });
        $("#sub_content_submit").on('click', function () {
            if ($(this).text() === "退订") {
                sub_content_submit = 0;
                $(this).text("订阅");
                $(this).removeClass("active")
            } else if ($(this).text() === "订阅") {
                sub_content_submit = 1;
                $(this).text("退订");
                $(this).addClass("active")
            }
        });
        $("#sub_content_reject").on('click', function () {
            if ($(this).text() === "退订") {
                sub_content_reject = 0;
                $(this).text("订阅");
                $(this).removeClass("active")
            } else if ($(this).text() === "订阅") {
                sub_content_reject = 1;
                $(this).text("退订");
                $(this).addClass("active")
            }
        });
        $("#sub_content_pass").on('click', function () {
            if ($(this).text() === "退订") {
                sub_content_pass = 0;
                $(this).text("订阅");
                $(this).removeClass("active")
            } else if ($(this).text() === "订阅") {
                sub_content_pass = 1;
                $(this).text("退订");
                $(this).addClass("active")
            }
        });


        form.on('submit(company_submit)', async (data) => {
            // data.field.company_contacts = contacts_lists;
            // data.field.company_foreigns = foreign_lists;
            // data.field.seal_datas = seal_lists;

            data.field.SubContentCheck = sub_content_check;
            data.field.SubContentSubmit = sub_content_submit;
            data.field.SubContentReject = sub_content_reject;
            data.field.SubContentPass = sub_content_pass;


            if (companyId) {
                const result = await admin.patch(`/company/update/${companyId}`, data.field);
                if (result.status) {
                    admin.reloadFrame('企业客户管理iframe');
                }
            } else {
                const result = await admin.post("@{{ urlfor "CompanyController.Store" }}", data.field);
                if (result.status) {
                    admin.reloadFrame('企业客户管理iframe');
                    setTimeout(() => {
                        parent.layui.admin.closeThisTabs()
                    }, 2000)
                }
            }
        });
    });

</script>